<template>
  <div>
    <el-form
      ref="ruleForm"
      :model="department"
      status-icon
      :rules="rules"
      label-width="80px"
    >
      <el-form-item label="院系编号" prop="departmentNo">
        <el-input
          readonly
          v-model="department.departmentNo"
          placeholder="请输入编号"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item label="院系名称" prop="departmentName">
        <el-input
          v-model="department.departmentName"
          placeholder="请输入名称"
        ></el-input>
      </el-form-item>
      <el-form-item label="院长" prop="departmentLeader">
        <el-select
          v-model="department.departmentLeader"
          placeholder="请选择院长"
        >
          <el-option
            v-for="item in this.deans"
            :key="item._id"
            :label="item.deanName"
            :value="item.deanNo"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="创建日期" prop="departmentCreateDate">
        <el-date-picker
          v-model="department.departmentCreateDate"
          type="date"
          placeholder="请选择创建日期"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="学生人数" prop="studentNumber">
        <el-input
         type="number"
          v-model="department.studentNumber"
          placeholder="请输入人数"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')"
          >提交</el-button
        >
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { nanoid } from "nanoid";
import rules from "../commons/validate";

import { useAddDepartment, useGetDeans } from "@/hooks/department";

export default {
  name: "DepartmentAdd",
  data() {
    return {
      rules,
      deans: [],
      department: {
        departmentNo: nanoid(),
        departmentName: "",
        departmentLeader: "",
        departmentCreateDate: "",
        studentNumber: "",
      },
    };
  },

  mounted() {
    (async () => {
      this.deans = (await useGetDeans())?.data?.deans;
    })();
  },

  methods: {
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          this.department.departmentCreateDate = new Date(this.department.departmentCreateDate).getTime();
          const resInfo = await useAddDepartment(this.department);
          if(resInfo.code === 201 && resInfo.message === 'success'){
               this.$message.success("添加成功")
          }else{
            this.$message.success("添加失败")
          }
        } else {
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  },
};
</script>

<style lang="scss" scoped></style>
